package com.sdry.product.prod.service;
import	java.util.HashSet;
import java.sql.Timestamp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sdry.basic.entity.Container;
import com.sdry.basic.entity.Material;
import com.sdry.product.prod.entity.ProductHandleOut;
import com.sdry.product.prod.entity.ResultAppList;
import com.sdry.product.prod.mapper.ProductHandleOutMapper;
import com.sdry.product.sorting.entity.SortFrame;
import com.sdry.product.sorting.mapper.SortReceivingDetailMapper;
import com.sdry.product.sorting.mapper.SortReceivingMapper;
import com.sdry.product.sorting.mapper.SortingStockMapper;
import com.sdry.untils.CustomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * (ProductHandleOut)表服务实现类
 *
 * @author makejava
 * @since 2020-03-03 17:49:29
 */
@Service("productHandleOutService")
@Transactional(rollbackFor = Exception.class)
public class ProductHandleOutServiceImpl extends ServiceImpl<ProductHandleOutMapper,ProductHandleOut> implements ProductHandleOutService {

    @Resource
    private ProductHandleOutMapper productHandleOutDao;

    @Resource
    private SortReceivingDetailMapper sortReceivingDetailMapper;

    @Resource
    private SortReceivingMapper sortReceivingMapper;

    @Resource
    private SortingStockMapper sortingStockMapper;

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<ProductHandleOut> queryAllByLimit(int offset, int limit) {
        return this.productHandleOutDao.queryAllByLimit(offset, limit);
    }

    @Override
    public void addPreTreatmentOut(String json, String userId) {
        Gson gson = new Gson();
        List<ResultAppList<Material>> resultAppList = gson.fromJson(json, new TypeToken<List<ResultAppList<Material>>>() {}.getType());
        for (ResultAppList<Material> materialResultAppList : resultAppList) {
            //验证库存是否存在，去除前处理区
            CustomUtil.verifyStockContainerExceptQcl(materialResultAppList.getPsId(),sortReceivingMapper);
            List<Material> materialList = materialResultAppList.getList();
            for (Material material : materialList) {
                ProductHandleOut product = new ProductHandleOut();
                //产品数量
                product.setQuantity(material.getQuantity());
                //去往哪里
                product.setGoSource(materialResultAppList.getCode());
                //修改人员
                product.setUpdateBy(userId);
                //修改人员
                product.setUpdateDate(new Timestamp(System.currentTimeMillis()));
                //状态变成1
                product.setStatus("2");
                QueryWrapper<ProductHandleOut> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("station_id",Long.parseLong(materialResultAppList.getPsId()))
                        .eq("status",0L).eq("materials_id",material.getMaId());
                productHandleOutDao.update(product,queryWrapper);

                String remark2 = "QCL-02";
                //更改容器装载数量
                sortReceivingDetailMapper.updateContainerStareQuantity(materialResultAppList.getPsId(),material.getMaId(),material.getQuantity(),userId,remark2);
                //装载表改状态
                sortReceivingDetailMapper.updateContainerStareStatus(Long.parseLong(materialResultAppList.getPsId()),userId,-2L);
            }
        }
    }

    @Override
    public List<ResultAppList<Material>> queryRegionPretreatmentMateriel(String permissionType) {
        List<Material> materialList = productHandleOutDao.queryRegionPretreatmentMateriel(permissionType);
        return CustomUtil.QueryResultChange(materialList);
    }

    @Override
    public void addPreTreatment(String json, String userId) {
        Gson gson = new Gson();
        List<ResultAppList<Material>> resultAppList = gson.fromJson(json, new TypeToken<List<ResultAppList<Material>>>() {}.getType());
        for (ResultAppList<Material> materialResultAppList : resultAppList) {
            //验证库存是否存在，去除分拣区
            CustomUtil.verifyStockContainerExceptFj(materialResultAppList.getPsId(),sortReceivingMapper);
            List<Material> materialList = materialResultAppList.getList();
            for (Material material : materialList) {
                ProductHandleOut product = new ProductHandleOut();
                //工位编号
                product.setStationNumber(materialResultAppList.getPsnumber());
                //工位ID
                product.setStationId(Long.parseLong(materialResultAppList.getPsId()));

                //物料ID
                product.setMaterialsId(material.getMaId());
                //产品数量
                product.setQuantity(material.getQuantity());
                //喷涂要求
                product.setSprayingRequirements(material.getMaSprayingRequirements());
                //紧急程度
                product.setEmergencyLevel(material.getUrgent());
                //操作人员
                product.setCreateBy(userId);

                String remark2 = "QCL-01";
                //更改容器装载数量
                sortReceivingDetailMapper.updateContainerStareQuantity(materialResultAppList.getPsId(),material.getMaId(),material.getQuantity(),userId,remark2);
                //装载表改状态
                sortReceivingDetailMapper.updateContainerStareStatus(Long.parseLong(materialResultAppList.getPsId()),userId,-2L);

                //更改容器装载记录表状态
                sortReceivingDetailMapper.updateTransitOrderRecordStatus(materialResultAppList.getPsId(),material.getMaId());

                //更改分拣区状态来源ID
                QueryWrapper<SortFrame> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("status",2L)
                        .eq("container_id",materialResultAppList.getPsId());
                SortFrame sortFrame = new SortFrame();
                sortFrame.setSource(materialResultAppList.getPsId());
                //来源的工位ID
                int update = sortingStockMapper.update(sortFrame, queryWrapper);
                if (update>0){
                    //来源
                    product.setSource("FJ");
                }else {
                    //来源
                    product.setSource("WZZ");
                }
                productHandleOutDao.insert(product);
            }
        }
    }

    @Override
    public List<ProductHandleOut> queryPreHangingLinePage(ProductHandleOut productHandleOut) {
        String status = productHandleOut.getStatus();
        String[] statusList = status.split(",");
        String stationNumber = productHandleOut.getStationNumber();
        if (StringUtils.isBlank(productHandleOut.getStationNumber())){
            stationNumber = null;
        }
        Long page = productHandleOut.getPage();
        Long limit = productHandleOut.getLimit();

        Map<String, Object> params = new HashMap<String, Object>(4);
        params.put("page",page);
        params.put("limit",limit);
        params.put("statusList",statusList);
        params.put("stationNumber",stationNumber);
        return productHandleOutDao.queryPreHangingLinePage(params);
    }

    @Override
    public Long queryPreHangingLineTotal(ProductHandleOut productHandleOut) {
        String[] statusList = productHandleOut.getStatus().split(",");
        String stationNumber = productHandleOut.getStationNumber();
        if (StringUtils.isBlank(productHandleOut.getStationNumber())){
            stationNumber = null;
        }
        Map<String, Object> params = new HashMap<String, Object>(4);
        params.put("statusList",statusList);
        params.put("stationNumber",stationNumber);
        return productHandleOutDao.queryPreHangingLineTotal(params);
    }

    @Override
    public List<Container> queryTransitAreaNumber() {
        return productHandleOutDao.queryTransitAreaNumber();
    }

    @Override
    public List<ResultAppList> queryProductHandleMateriel(String psnumber) {
        String[] str = psnumber.split(",");
        List<ResultAppList> resultAppListList = new ArrayList<>();
        for (String psNumber : str) {
            List<Material> materials = productHandleOutDao.queryProductHandleMateriel(psNumber);
            ResultAppList resultAppList = new ResultAppList();
            if (materials != null || materials.size() > 0) {
                for (Material material : materials) {
                    resultAppList.setPsId(material.getPsId());
                    resultAppList.setPsnumber(material.getPsnumber());
                    resultAppList.setList(materials);
                    resultAppList.setPaId(material.getPaId());
                }
            }else {
                resultAppList.setPsId("0");
                resultAppList.setPsnumber(psNumber);
            }
            resultAppListList.add(resultAppList);
        }
        return resultAppListList;
    }

    @Override
    public List<Container> queryProductHandleNumberByInfo() {
        List<Container> containers = new ArrayList<> ();
        Set<Container> containerHashSet = new HashSet<> ();

        QueryWrapper<ProductHandleOut> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0L).eq("status",0L);
        List<ProductHandleOut> productHandleOuts = productHandleOutDao.selectList(queryWrapper);
        for (ProductHandleOut productHandleOut : productHandleOuts) {
            Container container = new Container();
            container.setCid(productHandleOut.getStationId());
            container.setCnumber(productHandleOut.getStationNumber());
            containers.add(container);
        }
        containerHashSet.addAll(containers);
        containers.clear();
        containers.addAll(containerHashSet);
        return containers;
    }

    @Override
    public List<ResultAppList> queryProductHandleTransportMateriel(String psnumber) {
        String[] str = psnumber.split(",");
        List<ResultAppList> resultAppListList = new ArrayList<>();
        for (String psNumber : str) {
            List<Material> materials = productHandleOutDao.queryProductHandleTransportMateriel(psNumber);
            ResultAppList resultAppList = new ResultAppList();
            if (materials != null || materials.size() > 0) {
                for (Material material : materials) {
                    resultAppList.setPsId(material.getPsId());
                    resultAppList.setPsnumber(material.getPsnumber());
                    resultAppList.setList(materials);
                    resultAppList.setPaId(material.getPaId());
                }
            }else {
                resultAppList.setPsId("0");
                resultAppList.setPsnumber(psNumber);
            }
            resultAppListList.add(resultAppList);
        }
        return resultAppListList;
    }


}